<?php
header("Content-type: text/html; charset=utf-8");
$current_banben=include('../YunweiData/conf/version.php');
$update_banben='YunWeiCms20140822';
$need_banben='';

if($current_banben<$need_banben){
	exit('请升级到'.$need_banben.'后再升级此补丁');
}
if($current_banben>=$update_banben){
	exit('您已经升级过此版本了,请不要重复升级！');
}

$arr = require("../YunweiData/conf/db.php");
$dbpre=$arr['DB_PREFIX'];
$conn =mysql_connect($arr['DB_HOST'],$arr['DB_USER'],$arr['DB_PWD']) or die("连接数据库失败!");
mysql_select_db($arr['DB_NAME'],$conn);
mysql_query("set names utf8");


echo '创建数据表开始...<br>';
$sqlfile = 'update.sql';
$sqls = _get_sql($sqlfile);
foreach ($sqls as $sql) {
	//替换前缀
	$sql = str_replace('`wy_', '`' . $dbpre, $sql);
	$run = mysql_query($sql, $conn);
	//获得表名
	if (substr($sql, 0, 12) == 'CREATE TABLE') {
		$table_name = $dbpre . preg_replace("/CREATE TABLE `" . $dbpre . "([a-z0-9_]+)` .*/is", "\\1", $sql);
		echo $table_name.'云微CMS温馨提示: 版本更新成功...<br>';
	}
} 

file_put_contents('../YunweiData/conf/update.log',$update_banben.' '.date('Y-m-d H:i:s')."\r\n",FILE_APPEND);
file_put_contents('../YunweiData/conf/version.php','<?php return '.$update_banben.';?>');
echo "<br>云微CMS温馨提示: 执行更新结束！";

function _get_sql($sql_file) {
	$contents = file_get_contents($sql_file);
	$contents = str_replace("\r\n", "\n", $contents);
	$contents = trim(str_replace("\r", "\n", $contents));
	$return_items = $items = array();
	$items = explode(";\n", $contents);

	foreach ($items as $item) {
		$return_item = '';
		$item = trim($item);
		$lines = explode("\n", $item);
		foreach ($lines as $line) {
			if (isset($line[1]) && $line[0] . $line[1] == '--') {
				continue;
			}
			$return_item .= $line;
		}
		if ($return_item) {
			$return_items[] = $return_item; //.";";
		}
	}
	return $return_items;
}
?>	